package com.kady.controller.food;

import com.alibaba.fastjson.JSON;
import com.kady.contant.BeanFactoryConstant;
import com.kady.contant.ExceptionConstant;
import com.kady.contant.MessageConstant;
import com.kady.controller.BaseServlet;
import com.kady.entity.Food;
import com.kady.entity.FoodType;
import com.kady.entity.ResultVO;
import com.kady.factory.BeanFactory;
import com.kady.service.FoodService;
import com.kady.service.FoodTypeService;
import com.kady.service.OrderService;
import com.kady.utils.UploadUtil;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: kady
 * \* Date: 2021/3/25
 * \* Time: 14:21
 * \* 千峰JAVA2101班
 * \* Description: 菜品servlet类
 * \
 */
@WebServlet("/backend/food")
@MultipartConfig
public class FoodController extends BaseServlet {
    private FoodService foodService = (FoodService) BeanFactory.getBean(BeanFactoryConstant.FOOD_SERVICE);
    private OrderService orderService = (OrderService)BeanFactory.getBean(BeanFactoryConstant.ORDER_SERVICE);

    /**
     *获取菜品列表接口
     */
    public String list (HttpServletRequest req, HttpServletResponse resp) throws SQLException, InvocationTargetException, IllegalAccessException {
        String keyword = req.getParameter("keyword");
        List<Food> list = foodService.getFoodList(keyword);
        req.setAttribute("foods", list);
        req.setAttribute("keyword", keyword==null?"":keyword);
        return MessageConstant.PREFIX_FORWARD + "/backend/detail/food/food-list.jsp";
    }

    /**
     * 菜品添加
     */
    public Object save (HttpServletRequest req, HttpServletResponse resp) throws SQLException, InvocationTargetException, IllegalAccessException, IOException, ServletException {
        Map<String,String[]> reqData = req.getParameterMap();
        Object uploadRes = UploadUtil.uploadFile(req,"foodImage","/uploadFold/");
        /**
         * 判断拿到的上传路径对象是否为空
         */
        if(uploadRes!=null){
            if(uploadRes instanceof ResultVO){
                return uploadRes;
            }else if(uploadRes instanceof String){
                Food food = new Food();
                BeanUtils.populate(food,reqData);
                food.setFoodImage((String)uploadRes);
                foodService.addFood(food);
                return MessageConstant.PREFIX_FORWARD + "/backend/food?method=list";
            }
        }

        return new ResultVO(false, ExceptionConstant.UPLOAD_FILE);
    }

    /**
     * 菜品修改
     */
    public Object update (HttpServletRequest req, HttpServletResponse resp) throws SQLException, InvocationTargetException, IllegalAccessException, IOException, ServletException {
        Map<String,String[]> reqData = req.getParameterMap();
        Object uploadRes = UploadUtil.uploadFile(req,"foodImage","/uploadFold/");

        Food food = new Food();
        BeanUtils.populate(food,reqData);

        if(uploadRes instanceof ResultVO){
//                return uploadRes;//如果修改不上传图片就弹窗
            /**
             * 没有上传文件，把原来的图片路径赋值回去
             */
            food.setFoodImage(reqData.get("image")[0]);
            foodService.updateFood(food);
            return MessageConstant.PREFIX_FORWARD + "/backend/food?method=list";
        }else if(uploadRes instanceof String){
            /**
             * 有重新上传图片的情况
             */
            food.setFoodImage((String)uploadRes);
            foodService.updateFood(food);
            return MessageConstant.PREFIX_FORWARD + "/backend/food?method=list";
        }

        return new ResultVO(false, ExceptionConstant.UPLOAD_FILE);
    }

    /**
     * 菜品删除
     */
    public Object delete (HttpServletRequest req, HttpServletResponse resp) throws SQLException {
        String foodId = req.getParameter("foodId");
        /**
         * 统计已经在订单中的菜品，如果有就不要删除菜品
         */
        long countRes = orderService.countDetailsById(foodId);
        if(countRes>0L){
            return new ResultVO(false,ExceptionConstant.EXIST_FOOD_IN_DETAIL);
        }
        foodService.removeFood(foodId);

        return MessageConstant.PREFIX_FORWARD + "/backend/food?method=list";
    }


    /**
     * 上传文件的公共方法
     */

    /*public Object uploadFile(HttpServletRequest req,String partName,String filePath) throws IOException, ServletException {
        Part part = req.getPart(partName);
//        part.getSubmittedFileName()
        String cd = part.getHeader("Content-Disposition");
        //截取不同类型的文件需要自行判断
        String filename = cd.substring(cd.lastIndexOf("=")+2, cd.length()-1);

        //判断文件是否为空
        if(filename.isEmpty()){
            return new ResultVO(false, ExceptionConstant.NOT_FILE_UPLOAD);
        }
        //获取文件后缀名并创建新的文件名
        String suffixName = filename.substring(filename.lastIndexOf(MessageConstant.POINT));
        String newFileName = UUID.randomUUID().toString().replaceAll("-","").concat(suffixName);
        //获取文件上传的目标路径
        String uploadPath = req.getSession().getServletContext().getRealPath(filePath);

        File file = new File(uploadPath,newFileName);

        if(!file.getParentFile().exists()){
            file.getParentFile().mkdir();
        }

        part.write(uploadPath + newFileName);

        return uploadPath + newFileName;
    }*/

    /**
     * 使用名称查询菜品，校验菜品名称是否已存在
     */
    public String checkName(HttpServletRequest req,HttpServletResponse resp) throws SQLException {
        String name = req.getParameter("name");
        Food food = foodService.getFoodByName(name);
        if(food!=null){
            return JSON.toJSONString(food);
        }
        return null;
    }

}
